package com.jackrain.nea.fc.dl.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.util.TypeUtils;
import com.jackrain.nea.common.BtranEsName;
import com.jackrain.nea.common.PostHandleEvent;
import com.jackrain.nea.common.QueryDLUtil;
import com.jackrain.nea.core.redis.RedisObjectSerializer;
import com.jackrain.nea.dl.common.utils.esutil.ConvertQueryListUtil;
import com.jackrain.nea.dl.common.utils.esutil.ElasticsearchUtil;
import com.jackrain.nea.exception.NDSException;
import com.jackrain.nea.fc.dl.api.OmsDLTranOutSaveCmd;
import com.jackrain.nea.fc.dl.api.ViewDLQueryCmd;
import com.jackrain.nea.fc.dl.mapper.ViewDLTranOutMapper;
import com.jackrain.nea.fc.utils.Constants;
import com.jackrain.nea.sys.CommandAdapter;
import com.jackrain.nea.util.ApplicationContextHandle;
import com.jackrain.nea.util.ReferenceUtil;
import com.jackrain.nea.util.ValueHolder;
import com.jackrain.nea.web.face.User;
import com.jackrain.nea.web.query.DefaultWebEvent;
import com.jackrain.nea.web.query.QuerySessionImpl;
import com.jackrain.nea.web.security.Security4Utils;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

/**
 * 调拨出库单 oms->FC
 *
 * @author kangcog
 * @date 2018/10/18
 **/
@Slf4j
@Component
@Service(protocol = "dubbo", validation = "true", version = "1.0", group = "cp")
public class OmsDLTranOutSaveCmdImpl extends CommandAdapter implements OmsDLTranOutSaveCmd {

    @Autowired
    PostHandleEvent postHandleEvent;

    @Autowired
    private ElasticsearchUtil esUtil;

    @Autowired
    private ConvertQueryListUtil convertQLUtil;

    @Autowired
    private BtranEsName btranEsName;

    private RedisObjectSerializer serializer = new RedisObjectSerializer();

    @Reference(group = "dl", version = "1.0")
    private ViewDLQueryCmd viewDLQueryCmd;

    private Logger accesLogger = LoggerFactory.getLogger(Constants.ACCESS_PARAM_LOGGER);

    @Override
    public ValueHolder execute(HashMap map) throws NDSException {

//        log.info("----------OmsDLTranOutSaveCmdImpl----------" + map);
        ValueHolder vh = new ValueHolder();
        JSONObject param = JSON.parseObject(JSON.toJSONStringWithDateFormat(map.get("param"),
                "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteMapNullValue), Feature.OrderedField);
        log.info("OmsDLTranOutSaveCmdImpl--param-->{}",param);

        if (null == param || param.size() == 0) {
            throw new NDSException("参数格式错误！");
        }

        ViewDLTranOutMapper viewDLTranOutMapper = ApplicationContextHandle.getBean(ViewDLTranOutMapper.class);

        JSONArray paramArray = param.getJSONArray("data");

        JSONArray errorArray = new JSONArray();
        JSONArray successIds = new JSONArray();
        JSONArray spendTimeArray = new JSONArray();
        for (int i = 0; i < paramArray.size(); i++) {

            JSONObject errorJson = new JSONObject();
            JSONObject tranJson = paramArray.getJSONObject(i);

            JSONObject zbJS = tranJson.getJSONObject("DL_T_TRAN_TRANSFER");
            JSONArray itemJS = tranJson.getJSONArray("DL_T_TRAN_ITEM_TRANSFER");

            try {
                JSONObject spendTime = new JSONObject();
                Long retObjid = null;
                int status = 0;
                int sendStatus = 0;
                int accepteStatus = 0;
                String userName = zbJS.getString("OPR_ECODE");
                String idList = zbJS.getString("IDLIST");
                int autoCheck = zbJS.getInteger("AUTO_CHECK");
                int autoSend = zbJS.getInteger("AUTO_SEND");
                int autoAccept = zbJS.getInteger("AUTO_ACCEPT");
                String bill_No = zbJS.getString("BILL_NO");

                //如果原单号为C开头的零售单
                String from_bill_No = zbJS.getString("FROM_BILL_NO");
                if (from_bill_No != null) {
//                    String charindex = from_bill_No.substring(0, 1);
//                    if ("C".equals(charindex)) {
//                    log.info("-------------------oms零售单生成的调拨单开始处理---------" + tranJson);
                    //ES查询，根据原单号，查询单据ID
                    Long billID = null;
                    JSONObject jsonObject = es1(from_bill_No, btranEsName.getOuttype());
                    List<Long> tranBillIdList = convertQLUtil.selectId(jsonObject.toString());
                    if (null != tranBillIdList && tranBillIdList.size() > 0) {
                        billID = tranBillIdList.get(0);
                    }
//                    log.info("-------------------oms零售单生成的调拨单es---------" + jsonObject + ",ID=" + billID);
                    HashMap isExist1 = null;
                    if (null != billID) {
                        //原单号ID
                        String field1 = " ID,STATUS,SEND_STATUS,ACCEPTE_STATUS ";
                        JSONObject whereJS1 = new JSONObject();
                        whereJS1.put("ID", billID);
                        whereJS1.put("ISACTIVE", "Y");
                        isExist1 = QueryDLUtil.queryDL("DL_B_TRAN", field1, whereJS1);
//                        log.info("FROM_BILL_NO->" + from_bill_No + " isExist1->" + isExist1);
                    }

                    if (null != isExist1 && isExist1.size() > 0) {
                        status = TypeUtils.castToInt(isExist1.get("STATUS"));
                        retObjid = TypeUtils.castToLong(isExist1.get("ID"));
                        sendStatus = TypeUtils.castToInt(isExist1.get("SEND_STATUS"));
                        accepteStatus = TypeUtils.castToInt(isExist1.get("ACCEPTE_STATUS"));
                    }

//                    }
                }

                if (null != retObjid && retObjid > 0 && autoCheck != 1) {
                    successIds.add(idList);
                    continue;
                }

                if (2 == status && 1 == autoCheck && autoSend != 1) {
                    successIds.add(idList);
                    continue;
                }

                if (2 == sendStatus && 1 == autoSend && autoAccept != 1) {
                    successIds.add(idList);
                    continue;
                }

                if (2 == accepteStatus && autoAccept == 1) {
                    successIds.add(idList);
                    continue;
                }

                if (null == userName) {
                    userName = "root";
                }

                User user = Security4Utils.getUser(userName);
                String storeDate = zbJS.getString("STORE_DATE");

                //保存
                if (null == retObjid || retObjid <= 0) {
//                    log.info("-----" + bill_No + "-----OmsDLTranOutSaveCmdImpl--SAVE---START----------");
                    long saveStartTime = System.currentTimeMillis();
                    JSONObject resultJson = tranOutSaveData(tranJson, viewDLTranOutMapper);
                    accesLogger.info("OmsDLTranOutSaveCmdImpl--resultJson_save-->{}",resultJson);

                    QuerySessionImpl querySession = new QuerySessionImpl(user);
                    DefaultWebEvent event = new DefaultWebEvent("dlTranOut",
                            new HashMap(16));
                    event.put("param", resultJson);
                    String notic = "com.jackrain.nea.dl.tran.api.BtranoutbufferSaveCmd:1.0:dl";
                    event.put("command", notic);
                    event.put("table", "DL_B_TRAN_OUT");
                    event.setParameter("isSendMq", "N");
                    querySession.setEvent(event);
                    JSONObject retJo = postHandleEvent.executePostHandle(resultJson, querySession, event, "save");
                    double saveEndTime = (double) (System.currentTimeMillis() - saveStartTime) / 1000.0D;
                    spendTime.put("saveTime", saveEndTime);
                    spendTime.put("saveRetData", retJo);
//                    log.info("retJo=====>" + retJo.toString());
                    accesLogger.info("OmsDLTranOutSaveCmdImpl--retJo-->{}",retJo);

                    if (!retJo.containsKey("code")) {
                        throw new NDSException("保存返回值有误！无code");
                    }

                    if ((int) retJo.get("code") != 0) {
                        errorJson.put("key", idList);
                        if (null == retJo.get("message")) {
                            errorJson.put("message", "调拨出库单保存调用异常");
                        } else {
                            errorJson.put("message", "调拨出库单保存调用异常->" + retJo.get("message"));
                        }
                        errorArray.add(errorJson);
                        continue;
                    }
                    JSONObject retData = retJo.getJSONObject("data");
                    retObjid = retData.getLong("objid");
                }

                //调用提交
                if (2 != status && autoCheck == 1) {
//                    log.info("-----" + bill_No + "-----OmsDLTranOutSaveCmdImpl--SUMBIT---START----------");
                    long subStartTime = System.currentTimeMillis();
                    QuerySessionImpl querySession = new QuerySessionImpl(user);
                    DefaultWebEvent event = new DefaultWebEvent("dlTranOut", new HashMap(16));
                    String notic = "com.jackrain.nea.dl.tran.api.BtranoutSumbitCmd:1.0:dl";
                    JSONObject resultJson = new JSONObject();
                    resultJson.put("objid", retObjid);
                    resultJson.put("table", "DL_B_TRAN_OUT");
                    event.setParameter("isSendMq", "Y");
                    event.put("param", resultJson);
                    querySession.setEvent(event);
                    accesLogger.info("OmsDLTranOutSaveCmdImpl--resultJson_submit-->{}",resultJson);

                    //调用标准服务
                    JSONObject retSubJo = postHandleEvent.executePostHandle(resultJson, querySession, event, "submit");
                    double subEndTime = (double) (System.currentTimeMillis() - subStartTime) / 1000.0D;
                    spendTime.put("subEndTime", subEndTime);
                    spendTime.put("subRetData", retSubJo);
                    log.info("retSubJo=====>" + retSubJo);
                    accesLogger.info("OmsDLTranOutSaveCmdImpl--retSubJo-->{}",retSubJo);

                    if (!retSubJo.containsKey("code")) {
                        throw new NDSException("提交返回值有误！无code");
                    }

                    if ((int) retSubJo.get("code") != 0) {
                        errorJson.put("key", idList);
                        if (null == retSubJo.get("message")) {
                            errorJson.put("message", "调拨出库单提交调用异常");
                        } else {
                            errorJson.put("message", "调拨出库单提交调用异常->" + retSubJo.get("message"));
                        }
                        errorArray.add(errorJson);
                        continue;
                    }
                }

                //调用发出
                if (2 != sendStatus && autoSend == 1) {
//                    log.info("-----" + bill_No + "-----OmsDLTranOutSaveCmdImpl--SEND---START----------");
                    long sendStartTime = System.currentTimeMillis();
                    QuerySessionImpl querySession = new QuerySessionImpl(user);
                    DefaultWebEvent event = new DefaultWebEvent("dlTranOut", new HashMap(16));
                    String notic = "com.jackrain.nea.dl.tran.api.BtranoutSendCmd:1.0:dl";
                    JSONObject resultJson = new JSONObject();
                    resultJson.put("objid", retObjid);
                    resultJson.put("IS_F4CHECK", "N");
                    resultJson.put("table", "DL_B_TRAN_OUT");
                    event.setParameter("isSendMq", "Y");
                    event.put("param", resultJson);
                    event.setParameter("command", notic);
                    event.setParameter("webaction", "DL_B_TRAN_OUT_SEND_TRAFFIC_CONFIRM");
                    querySession.setEvent(event);
                    accesLogger.info("OmsDLTranOutSaveCmdImpl--resultJson_sendout-->{}",resultJson);

                    //调用标准服务
                    JSONObject retSendJo = postHandleEvent.executePostHandle(resultJson, querySession, event, "webaction");
                    double sendEndTime = (double) (System.currentTimeMillis() - sendStartTime) / 1000.0D;
                    spendTime.put("sendEndTime", sendEndTime);
                    spendTime.put("sendRetData", retSendJo);
                    accesLogger.info("OmsDLTranOutSaveCmdImpl--retSendJo-->{}",retSendJo);

                    if (!retSendJo.containsKey("code")) {
                        throw new NDSException("调拨单发出返回值有误！无code");
                    }

                    if ((int) retSendJo.get("code") != 0) {
                        errorJson.put("key", idList);
                        if (null == retSendJo.get("message")) {
                            errorJson.put("message", "调拨出库单发出调用异常");
                        } else {
                            errorJson.put("message", "调拨出库单发出调用异常->" + retSendJo.get("message"));
                        }
                        errorArray.add(errorJson);
                        continue;
                    }
                }

                //调用验收
                if (2 != accepteStatus && autoAccept == 1) {
//                    log.info("----------OmsDLTranOutSaveCmdImpl-- accpect1-----start-----");

                    long saveAcceptStartTime = System.currentTimeMillis();
                    DefaultWebEvent event = new DefaultWebEvent("dlTranOut", new HashMap(16));
                    QuerySessionImpl querySession = new QuerySessionImpl(user);

                    JSONObject tranJo = tranOutAcceptData(itemJS, retObjid);
                    event.put("param", tranJo);
                    event.setParameter("isSendMq", "N");
                    querySession.setEvent(event);
                    accesLogger.info("OmsDLTranOutSaveCmdImpl--tranJo-->{}",tranJo);

                    JSONObject retsaveAcceptJo = postHandleEvent.executePostHandle(tranJo, querySession, event, "save");

                    double saveAcceptEndTime = (double) (System.currentTimeMillis() - saveAcceptStartTime) / 1000.0D;
                    spendTime.put("saveAcceptEndTime", saveAcceptEndTime);
                    spendTime.put("retsaveAcceptJo", retsaveAcceptJo);
                    accesLogger.info("OmsDLTranOutSaveCmdImpl--retsaveAcceptJo-->{}",retsaveAcceptJo);
//                    log.info("retsaveAcceptJo==>" + retsaveAcceptJo.toString());
                    if (!retsaveAcceptJo.containsKey("code")) {
                        throw new NDSException("调拨单验收前保存返回值有误！无code");
                    }

                    if ((int) retsaveAcceptJo.get("code") != 0) {
                        errorJson.put("key", idList);
                        if (null == retsaveAcceptJo.get("message")) {
                            errorJson.put("message", "调拨入库单验收前保存操作服务调用异常");
                        } else {
                            errorJson.put("message", "调拨入库单验收前保存操作服务调用异常->" +
                                    retsaveAcceptJo.get("message"));
                        }
                        errorArray.add(errorJson);
                        continue;
                    }

                    long acceptStartTime = System.currentTimeMillis();
                    JSONObject paramJson = new JSONObject();
                    paramJson.put("objid", retObjid);
                    paramJson.put("ARRIVAL_TIME_APPLY", new Timestamp(System.currentTimeMillis()).toString());
                    paramJson.put("STORE_DATE_IN", storeDate);
                    paramJson.put("IS_F4CHECK", "N");
                    paramJson.put("is_check", "Y");
                    JSONObject fixColumn = new JSONObject();
                    fixColumn.put("DL_B_TRAN_IN", tranJo.get("DL_T_TRAN_TRANSFER"));
                    fixColumn.put("DL_B_TRAN_IN_V_ITEM_SKU", tranJo.get("DL_T_TRAN_ITEM_TRANSFER"));
                    paramJson.put("fixcolumn", fixColumn);

                    event.put("param", paramJson);
                    querySession.setEvent(event);
                    accesLogger.info("OmsDLTranOutSaveCmdImpl--paramJson-->{}",paramJson);
//                    log.info("CheckInparamJson==>" + paramJson.toString());
                    //调用验收服务
                    event.setParameter("command", "com.jackrain.nea.dl.tran.api.BtraninCheckInCmd:1.0:dl");
                    event.setParameter("table", "DL_B_TRAN_IN");
                    event.setParameter("webaction", "DL_B_TRAN_IN_CHECK_S");
                    event.setParameter("isSendMq", "Y");
                    querySession.setEvent(event);

                    JSONObject retAcceptJo = postHandleEvent.executePostHandle(paramJson, querySession, event, "webaction");
                    accesLogger.info("OmsDLTranOutSaveCmdImpl--retAcceptJo-->{}",retAcceptJo);

                    double acceptEndTime = (double) (System.currentTimeMillis() - acceptStartTime) / 1000.0D;
                    spendTime.put("acceptEndTime", acceptEndTime);
                    spendTime.put("retAcceptJo", retAcceptJo);

                    if (!retAcceptJo.containsKey("code")) {
                        throw new NDSException("调拨单验收返回值有误！无code");
                    }

                    if ((int) retAcceptJo.get("code") != 0) {
                        errorJson.put("key", idList);
                        if (null == retAcceptJo.get("message")) {
                            errorJson.put("message", "调拨出库单验收操作服务调用异常");
                        } else {
                            errorJson.put("message", "调拨出库单验收操作服务调用异常->" + retAcceptJo.get("message"));
                        }
                        errorArray.add(errorJson);
                        continue;
                    }
                }

                successIds.add(idList);
                spendTimeArray.add(spendTime);
            } catch (Exception e) {
                log.debug("生成调拨单异常" + e);
                String error = "";
                if ((e instanceof NDSException)) {
                    error = e.getMessage();
                } else {
                    StringWriter sw = new StringWriter();
                    PrintWriter pw = new PrintWriter(sw);
                    e.printStackTrace(pw);
                    error = sw.toString();
                }
                String idList = zbJS.getString("IDLIST");
                errorJson.put("key", idList);
                errorJson.put("message", error);
                errorArray.add(errorJson);
            }
        }

        if (errorArray.size() > 0) {
            vh.put("error", errorArray);
            vh.put("code", -1);
        } else {
            vh.put("code", 0);
        }
        vh.put("successIds", successIds);
        vh.put("spendTime", spendTimeArray);

        return vh;
    }

    private JSONObject tranOutAcceptData(JSONArray itemJS, Long retObjid) throws Exception {
        String fcItemTableNmae = "dl_b_tran_item_sku";
        JSONArray tranInArray = new JSONArray();
        for (int j = 0; j < itemJS.size(); j++) {
            JSONObject itemJson = itemJS.getJSONObject(j);
            JSONObject newItemJson = new JSONObject();
            String sku = itemJson.getString("PS_C_SKU_ECODE");
            //明细id
            String field2 = "ID";
            JSONObject whereJS2 = new JSONObject();
            whereJS2.put("DL_B_TRAN_ID", retObjid);
            whereJS2.put("PS_C_SKU_ECODE", sku);
            HashMap itemIdJson = QueryDLUtil.queryDL(fcItemTableNmae, field2, whereJS2);
            if (null != itemIdJson && itemIdJson.size() > 0) {
                newItemJson.put("ID", itemIdJson.get("ID"));
            }
            newItemJson.put("QTY_IN", itemJson.get("QTY_BILL"));
            tranInArray.add(newItemJson);
        }

        JSONObject tranJo = new JSONObject();
        JSONObject fixColumJo = new JSONObject();
        fixColumJo.put("DL_B_TRAN_IN_V_ITEM_SKU", tranInArray);
        tranJo.put("objid", retObjid);
        tranJo.put("IS_F4CHECK", "N");
        tranJo.put("fixcolumn", fixColumJo);
        tranJo.put("table", "DL_B_TRAN_IN");

        return tranJo;
    }

    private JSONObject tranOutSaveData(JSONObject tranJson, ViewDLTranOutMapper viewDLTranOutMapper) throws Exception {

        JSONObject zbJS = tranJson.getJSONObject("DL_T_TRAN_TRANSFER");
        JSONArray itemJS = tranJson.getJSONArray("DL_T_TRAN_ITEM_TRANSFER");

        //明细款
        StringBuffer ecodeList = new StringBuffer();
        //明细款名称
        StringBuffer enameList = new StringBuffer();
        //调拨数量合计
        BigDecimal sumQtyBill = BigDecimal.ZERO;
        //调拨金额合计
        BigDecimal sumAmtList = BigDecimal.ZERO;
        //品类ID集合
        StringBuffer departIdList = new StringBuffer();

        log.info("-------处理明细表数据-----");
        /*************处理明细表数据************/
        List<String> proEcodeList = new ArrayList();
        List<Long> departList = new ArrayList();
        for (int j = 0; j < itemJS.size(); j++) {
            JSONObject itemJson = itemJS.getJSONObject(j);
            itemJson.put("ID", -1);
            itemJson.put("ISACTIVE", "Y");

            //商品ID
            if (null != itemJson.getString("PS_C_SKU_ECODE")) {
                String skuEcode = itemJson.getString("PS_C_SKU_ECODE");
                HashMap h = viewDLTranOutMapper.selSkuData(skuEcode);

                if (null != h && h.size() > 0) {
                    //条码ID
                    itemJson.put("PS_C_SKU_ID", h.get("ID"));
                    if (null != h.get("PS_C_PRO_ID")) {
                        //商品ID
                        itemJson.put("PS_C_PRO_ID", h.get("PS_C_PRO_ID"));
                        HashMap proHashMap = viewDLTranOutMapper.selProData((Long) h.get("PS_C_PRO_ID"));

                        if (null != proHashMap && proHashMap.size() > 0) {
                            //商品编码
                            itemJson.put("PS_C_PRO_ECODE", proHashMap.get("ECODE"));
                            //商品名称
                            itemJson.put("PS_C_PRO_ENAME", proHashMap.get("ENAME"));
                            //商品图片
                            itemJson.put("PS_C_PRO_IMAGE", proHashMap.get("IMAGE"));
                            //品类ID
                            itemJson.put("PRO_TYPE_DEPART_ID", proHashMap.get("NUMDIM26"));
                        } else {
                            throw new NDSException("商品档案 查询为空！  商品ID：" + h.get("PS_C_PRO_ID"));
                        }

                        if (itemJson.containsKey("PRO_TYPE_DEPART_ID") &&
                                (null != itemJson.getLong("PRO_TYPE_DEPART_ID"))) {
                            HashMap proDimHashMap = viewDLTranOutMapper.selProItemData(itemJson.getLong("PRO_TYPE_DEPART_ID"));

                            if (null != proDimHashMap && proDimHashMap.size() > 0) {
                                //品类编码
                                itemJson.put("PRO_TYPE_DEPART_ECODE", proDimHashMap.get("ECODE"));
                                //品类名称
                                itemJson.put("PRO_TYPE_DEPART_ENAME", proDimHashMap.get("ENAME"));
                            }
                        }
                    }
                    if (null != h.get("PS_C_SPEC1OBJ_ID")) {
                        //颜色ID
                        itemJson.put("PS_C_CLR_ID", h.get("PS_C_SPEC1OBJ_ID"));
                        HashMap specobj = viewDLTranOutMapper.selSpecobjData((Long) h.get("PS_C_SPEC1OBJ_ID"));

                        if (null != specobj && specobj.size() > 0) {
                            //颜色编码
                            itemJson.put("PS_C_CLR_ECODE", specobj.get("ECODE"));
                            //颜色名称
                            itemJson.put("PS_C_CLR_ENAME", specobj.get("ENAME"));
                        }
                    }
                    if (null != h.get("PS_C_SPEC2OBJ_ID")) {
                        //尺寸ID
                        itemJson.put("PS_C_SIZE_ID", h.get("PS_C_SPEC2OBJ_ID"));
                        HashMap specobj = viewDLTranOutMapper.selSpecobjData((Long) h.get("PS_C_SPEC2OBJ_ID"));
                        if (null != specobj && specobj.size() > 0) {
                            //尺寸编码
                            itemJson.put("PS_C_SIZE_ECODE", specobj.get("ECODE"));
                            //尺寸名称
                            itemJson.put("PS_C_SIZE_ENAME", specobj.get("ENAME"));
                        }
                    }
                } else {
                    throw new NDSException("SKU 查询为空！  sku编码：" + skuEcode);
                }
            }
            //是否缓冲补货
            Integer isBfSupply = itemJson.getInteger("IS_BF_SUPPLY");
            if (null != isBfSupply) {
                if (1 == isBfSupply) {
                    itemJson.put("IS_BF_SUPPLY", "Y");
                } else if (0 == isBfSupply) {
                    itemJson.put("IS_BF_SUPPLY", "N");
                } else {
                    log.info("无法判定是否为缓冲生成 isBfSupply:" + isBfSupply);
                }
            }

            if (null != itemJson.getString("PS_C_PRO_ECODE")) {
                String ecode = itemJson.getString("PS_C_PRO_ECODE");
                if (!proEcodeList.contains(ecode)) {
                    proEcodeList.add(ecode);
                    ecodeList.append(ecode + ",");
                    enameList.append(itemJson.getString("PS_C_PRO_ENAME") + ",");
                }
            }

            if (null != itemJson.getString("PRO_TYPE_DEPART_ID")) {
                Long departId = itemJson.getLong("PRO_TYPE_DEPART_ID");
                if (!departList.contains(departId)) {
                    departList.add(departId);
                    departIdList.append(departId + ",");
                }
            }
            sumQtyBill = sumQtyBill.add(itemJson.getBigDecimal("QTY_BILL"));
            sumAmtList = sumAmtList.add(itemJson.getBigDecimal("AMT_BILL"));
        }

        if (ecodeList.length() > 0) {
            ecodeList.deleteCharAt(ecodeList.length() - 1);
        }
        if (enameList.length() > 0) {
            enameList.deleteCharAt(enameList.length() - 1);
        }
        if (departIdList.length() > 0) {
            departIdList.deleteCharAt(departIdList.length() - 1);
        }

        log.info("-------处理主表数据-----");
        /*************处理主表数据************/

        JSONObject newzbJson = new JSONObject();
        Set<String> keySet = zbJS.keySet();
        for (String key : keySet) {
            if ("OPR_ECODE".equals(key) || "IDLIST".equals(key) || "AUTO_CHECK".equals(key) ||
                    "AUTO_SEND".equals(key) || "AUTO_ACCEPT".equals(key)) {
                continue;
            } else {
                newzbJson.put(key, zbJS.get(key));
            }
        }

        if (zbJS.containsKey("CP_C_ORIG_ECODE") && (null != zbJS.getString("CP_C_ORIG_ECODE"))) {
            String ecode = zbJS.getString("CP_C_ORIG_ECODE");
            HashMap h = viewDLTranOutMapper.selStoreData(ecode);
            if (null != h && h.size() > 0) {
                //发货店仓ID
                newzbJson.put("CP_C_ORIG_ID", h.get("ID"));
            } else {
                throw new NDSException("店仓 查询为空   店仓编码:" + ecode);
            }
        }

        if (zbJS.containsKey("CP_C_DEST_ECODE") && (null != zbJS.getString("CP_C_DEST_ECODE"))) {
            String ecode = zbJS.getString("CP_C_DEST_ECODE");
            HashMap h = viewDLTranOutMapper.selStoreData(ecode);
            if (null != h && h.size() > 0) {
                //收货店仓ID
                newzbJson.put("CP_C_DEST_ID", h.get("ID"));
                //物流批次
                newzbJson.put("LOGISTICS", h.get("LOGISTICS"));
            } else {
                throw new NDSException("店仓 查询为空   店仓编码:" + ecode);
            }
        }

        //单据类型
        String billType = zbJS.getString("BILL_TYPE");
        //原单号编码
        String billEcode = zbJS.getString("FROM_BILL_NO");
        Long billID = null;
        if (null != billType && null != billEcode) {
            if ("newtrial".equals(billType) || "newmarket".equals(billType)) {
                //ES查询
                JSONObject jsonObject = es(billEcode, btranEsName.getPlantype());
                List<Long> planBillIdList = convertQLUtil.selectId(jsonObject.toString());
                if (null != planBillIdList && planBillIdList.size() > 0) {
                    billID = planBillIdList.get(0);
                }
                if (null != billID) {
                    //原单号ID
                    newzbJson.put("FROM_BILL_ID", billID);
                }
            } else if ("tran".equals(billType) || "buffer".equals(billType)) {
                //ES查询
                JSONObject jsonObject = es(billEcode, btranEsName.getOuttype());
                List<Long> tranBillIdList = convertQLUtil.selectId(jsonObject.toString());
                if (null != tranBillIdList && tranBillIdList.size() > 0) {
                    billID = tranBillIdList.get(0);
                }
                if (null != billID) {
                    //原单号ID
                    newzbJson.put("FROM_BILL_ID", billID);
                }
            } else {
                log.error("billType==>" + billType);
            }
        }

        String addType = zbJS.getString("ADD_TYPE_ID");
        if (null != addType) {
            JSONObject paramObject1 = new JSONObject();
            String sql = "SELECT ID FROM DL_C_BILLDIM_ITEM " +
                    "WHERE ECODE='" + addType + "' AND DL_C_BILLDIM_ID " +
                    "IN (SELECT ID FROM DL_C_BILLDIM WHERE TAG='TRANADD_TYPE')";
            paramObject1.put("dlsql", sql);

            HashMap queryDlmap = new HashMap(16);
            queryDlmap.put("param", paramObject1);
            Object o = ReferenceUtil.refer(ApplicationContextHandle.getApplicationContext(),
                    "com.jackrain.nea.fc.dl.api.ViewDLQueryCmd",
                    "dl", "1.0");
            ValueHolder result = ((ViewDLQueryCmd) o).execute(queryDlmap);
            JSONObject selectMenuType = result.toJSONObject();
            byte[] dlbyte = selectMenuType.getString("dlLsit").getBytes("ISO-8859-1");
            List<HashMap> typeIDList = (List<HashMap>) serializer.deserialize(dlbyte);
            Long addTypeId = null;
            if (null != typeIDList && typeIDList.size() > 0) {
                log.info("typeIDList->");
                HashMap addTypeHash = typeIDList.get(0);
                addTypeId = TypeUtils.castToLong(addTypeHash.get("ID"));
            }
            if (null != addTypeId) {
                //加补类型
                newzbJson.put("ADD_TYPE_ID", addTypeId);
            } else {
                newzbJson.put("ADD_TYPE_ID", null);
            }
        }

        //编码集合
        newzbJson.put("PS_C_PRO_ECODE_LIST", ecodeList);
        //名称集合
        newzbJson.put("PS_C_PRO_ENAME_LIST", enameList);
        //调拨数量合计
        newzbJson.put("SUM_QTY_BILL", sumQtyBill);
        //调拨金额合计
        newzbJson.put("SUM_AMT_LIST", sumAmtList);
        //品类ID集合
        newzbJson.put("PRO_TYPE_DEPART_ID_LIST", departIdList);

        JSONObject fixColumn = new JSONObject();
        fixColumn.put("DL_B_TRAN_OUT", newzbJson);
        fixColumn.put("DL_B_TRAN_OUT_V_ITEM_SKU", itemJS);

        JSONObject resultJson = new JSONObject();
        resultJson.put("objid", -1);
        resultJson.put("fixcolumn", fixColumn);
        resultJson.put("table", "DL_B_TRAN_OUT");

        log.info("resultJson==>" + resultJson.toString());

        return resultJson;
    }


    /**
     * ES查询
     *
     * @param billNo 单据编号
     * @return id
     */
    public JSONObject es(String billNo, String type) {
        JSONObject bill_no = esUtil.generateMatch("BILL_NO", billNo);
        List<JSONObject> terms = esUtil.packageTerm(bill_no);
//        List<Long> longs = null;
        JSONObject jsonObject = null;
        try {
            jsonObject = esUtil.searchAllDataByTerms(btranEsName.getIndex(),
                    type, "1", "10000", terms);
            log.debug("es_jsonObject->" + jsonObject);
//            longs = convertQLUtil.selectId(jsonObject.toString());
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        return jsonObject;
    }

    /**
     * ES查询
     *
     * @param fromBillNo 单据原单号
     * @return id
     */
    public JSONObject es1(String fromBillNo, String type) {
        JSONObject bill_no = esUtil.generateMatch("FROM_BILL_NO", fromBillNo);
        List<JSONObject> terms = esUtil.packageTerm(bill_no);
//        List<Long> longs = null;
        JSONObject jsonObject = null;
        try {
            jsonObject = esUtil.searchAllDataByTerms(btranEsName.getIndex(),
                    type, "1", "10000", terms);
            log.debug("es_jsonObject->" + jsonObject);
//            longs = convertQLUtil.selectId(jsonObject.toString());
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        return jsonObject;
    }


    private JSONObject billdata(JSONObject esData) {
        JSONObject hits = esData.getJSONObject("hits");
        JSONArray hitsArray = hits.getJSONArray("hits");
        JSONObject sourceJson = hitsArray.getJSONObject(0);

        JSONObject source = sourceJson.getJSONObject("_source");

        return source;
    }

}
